<?php
/**
 * Created by PhpStorm.
 * Task: xuxiaoming
 * Date: 2017/11/7
 * Time: 17:55
 */

namespace App\Http\Controllers;


use App\Models\Task;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;

class TaskController extends Controller
{
    /**
     * 列表
     * @return string
     */
    public function index()
    {
        $tasks = Task::orderBy("sort", request()->get("sort", "asc"))->get();
        if ($tasks) {
            return sendJsonData($tasks->toArray());
        } else {
            return sendJsonMessage('数据不存在', true);
        }
    }


    /**
     * 列表
     * @param Request $request
     * @return string
     */
    public function getTask(Request $request, $id)
    {
        $task = Task::find($id);
        if ($task) {
            return sendJsonData($task->toArray());
        } else {
            return sendJsonMessage('数据不存在', true);
        }
    }

    /**
     * 创建用户
     * @param Request $request
     * @return string
     */
    public function createTask(Request $request)
    {
        $tasks = Task::create($request->all());

        return sendJsonData($tasks->toArray());
    }

    /**
     * 更新用户
     *
     * @param Request $request
     * @param $id
     * @return string
     */
    public function updateTask(Request $request, $id)
    {
        $tasks = Task::find($id);
        if ($tasks) {
            $tasks->project_id = $request->input('project_id');
            $tasks->module_id = $request->input('module_id');
            $tasks->title = $request->input('title');
            if ($request->input('state',"") != ""){
                if (in_array($request->input('state'), [0, 1, 2])) {
                    $tasks->state = $request->input('state');
                } else {
                    return sendJsonMessage('设置状态不正确');
                }
            }

            $tasks->save();
            return sendJsonData($tasks->toArray());
        } else {
            return sendJsonMessage('删除成功');
        }
    }

    /**
     * 更新状态
     *
     * @param Request $request 修改请求
     * @param int $id 任务ID
     * @param int $state 状态
     * @return string
     */
    public function updateTaskState(Request $request, $id, $state)
    {
        $tasks = Task::find($id);

        if ($tasks) {
            $tasks->state = $state;
            $tasks->save();
            return sendJsonData($tasks->toArray());
        } else {
            return sendJsonMessage('删除成功');
        }
    }

    /**
     * 删除用户
     *
     * @param $id
     * @return string
     */
    public function deleteTask($id)
    {
        $tasks = Task::find($id);
        if ($tasks) {
            $tasks->delete();
            return sendJsonMessage('删除成功');
        } else {
            return sendJsonMessage('数据不存在', true);
        }

    }


}